package com.yvan.leto.server.service;

import com.yvan.leto.ResourceFoundException;
import com.yvan.leto.server.dao.ProjectPersistent;
import com.yvan.leto.server.domain.Project;
import com.yvan.leto.server.domain.ReleaseUnit;
import com.yvan.leto.server.domain.Segment;
import com.yvan.platform.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class ApiService {

    @Autowired
    private ConfigParserService configParserService;

    @Autowired
    private ProjectPersistent projectPersistent;

    @Autowired
    private ReleaseService releaseService;

    /**
     * 根据当前工作目录，获取相应配置
     */
    public String debugMe(String env, String projectName, String segmentName) {
        Project project = projectPersistent.projectFindByName(projectName);

        for (Segment segment : project.getSegments()) {
            if (segmentName.equals(segment.getName())) {
                final IParser parser = configParserService.getParser(segment);
                return parser.process(new ParserContext(env, project, segment));
            }
        }
        throw new ResourceFoundException("project " + projectName + "'s segment \"" + segmentName + "\" not found!", projectName + "." + segmentName);
    }

    /**
     * 根据当前项目所在版本，获取相应配置
     */
    public String service(String env, String projectName, String segmentName) {
        return releaseService.getConfigResult(env, projectName, segmentName);
    }
}
